package com.wpml.cloud.myprovider.controller;

import com.wpml.cloud.myprovider.model.Person.Person;
import com.wpml.cloud.myprovider.service.PersonService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.List;
import java.util.stream.IntStream;

@RestController
@RequestMapping("person")
public class PersonController {

    static final Logger LOGGER = LogManager.getLogger(PersonController.class);

    @Autowired
    PersonService personService;

    @PostMapping("post")
    public void post(ServerHttpRequest request, Person person) {
        Flux<DataBuffer> body = request.getBody();

        System.out.println(body);
        System.out.println(person);
    }

    @GetMapping("getById/{idVal}")
    public Mono<Person> getById(@PathVariable Integer idVal){
        Mono<Person> result = null;
        try {
            LOGGER.info("=======获取数据开始======");

            result = personService.getById(idVal);

            LOGGER.info("=======获取数据结束======");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @GetMapping("getOne")
    public Mono<Person> getOne(int id, ServerHttpRequest request) {
        List<String> id1 = request.getQueryParams().get("id");

        System.out.println(id1);

        System.out.println("-------1-------");
        /*Person one = personService.getOne(id);

        Mono<Person> result = Mono.just(one);*/

        Mono<Person> result = Mono.create(sink -> {
            Person one = personService.getOne(id);
            sink.success(one);
        });

        System.out.println("-------2-------");

        return result;

    }

    @GetMapping(value = "sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<Person> sse() {
//        Flux<Person> personFlux = Flux.fromStream(IntStream.range(1, 10).mapToObj(id -> personService.getOne(id)));
        return Flux.fromStream(IntStream.range(1, 10).mapToObj(id -> personService.getOne(id)))
                .doOnSubscribe(sub -> System.out.println("=======sub 订阅======"))
                .doOnNext(d -> System.out.println("来数据了 " + d))
                .doOnComplete(() -> System.out.println("===doOnComplete=== 请求完成"));
    }

    @GetMapping("getAll")
    public Flux<Person> getAll() {

        return null;
    }
}
